﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using fanfu.Common;
using fanfu.Business;
using fanfu.Model;
using System.IO;
using System.Configuration;

public partial class Channel : BasePage
{
    //所有频道信息
    private DataTable __Channel = new DataTable();

    #region 自定义
    /// <summary>
    /// 绑定查询后的数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindDataBySearch(Repeater rptDataList, int page)
    {
        #region 获取查询条件

        //获取查询条件
        string channelName = this.searchChannelName.Value.Trim();
        string channelDes = this.searchChannelDes.Value.Trim();
        string startTime = this.searchStartCreateTime.Value.Trim();
        string endTime = this.searchEndCreateTime.Value.Trim();
        byte isEnd = byte.Parse(this.searchIsEnd.SelectedItem.Value);
        byte flag = byte.Parse(this.searchFlag.SelectedItem.Value);
        int parentId = int.Parse(this.searchParent.SelectedValue);
        #endregion

        #region 创建查询SQL语句和查询条件参数

        //创建查询SQL语句和查询条件参数
        string sqlString = "SELECT * FROM Channel WHERE 1=1 ";
        List<SqlParameter> paraList = new List<SqlParameter>();

        if (channelName != "")
        {
            sqlString += "AND ChannelName like @ChannelName ";
            paraList.Add(new SqlParameter("@ChannelName", "%" + channelName + "%"));
        }
        if (channelDes != "")
        {
            sqlString += "AND ChannelDes like @ChannelDes ";
            paraList.Add(new SqlParameter("@ChannelDes", "%" + channelDes + "%"));
        }
        if (startTime != "")
        {
            sqlString += "AND CreateTime>=@StartCreateTime ";
            paraList.Add(new SqlParameter("@StartCreateTime", Convert.ToDateTime(startTime)));
        }
        if (endTime != "")
        {
            sqlString += "AND CreateTime<@EndCreateTime ";
            paraList.Add(new SqlParameter("@EndCreateTime", Convert.ToDateTime(endTime).AddDays(1)));
        }
        if (isEnd != 0)
        {
            sqlString += "AND IsEnd=@IsEnd ";
            paraList.Add(new SqlParameter("@IsEnd", isEnd));
        }
        if (flag != 0)
        {
            sqlString += "AND Flag=@Flag ";
            paraList.Add(new SqlParameter("@Flag", flag));
        }
        if (parentId != -1)
        {
            sqlString += "AND ParentId=@ParentId ";
            paraList.Add(new SqlParameter("@ParentId", parentId));
        }
        sqlString += "ORDER BY ParentId ASC, Ord ASC";
        #endregion

        //给数据列表赋值
        __Channel = SqlHelper.GetDataTable(sqlString, paraList.ToArray());
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __Channel.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__Channel.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定全部数据到Repeater
    /// </summary>
    /// <param name="rptDataList">要绑定的Repeater对象</param>
    /// <param name="page">设置当前页,从1开始</param>
    private void BindAllData(Repeater rptDataList, int page)
    {
        //清理查询框数据,避免单击页码时产生错误条件
        this.searchChannelName.Value = "";
        this.searchChannelDes.Value = "";
        this.searchStartCreateTime.Value = "";
        this.searchEndCreateTime.Value = "";
        this.searchIsEnd.SelectedIndex = 0;
        this.searchFlag.SelectedIndex = 0;

        //给数据列表赋值
        __Channel = new ChannelRule().GetAllChannelInfo();
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = __Channel.DefaultView;
        pds.AllowPaging = true;
        pds.PageSize = __AdminPageSize;
        pds.CurrentPageIndex = page - 1;
        rptDataList.DataSource = pds;
        rptDataList.DataBind();

        //创建的分页HTML并赋值给前台
        this.paging.InnerHtml = CreateAdminPaging(__Channel.Rows.Count, page);
        //清理控件状态
        ClearInputState();
    }

    /// <summary>
    /// 绑定所有顶级频道到下拉列表
    /// </summary>
    private void BindChannelList(DropDownList channelList)
    {
        string selectString = "SELECT * FROM Channel WHERE ParentId=0 ORDER BY Ord ASC";
        DataTable systemMenu = SqlHelper.GetDataTable(selectString);
        if (systemMenu.Rows.Count > 0)
        {
            channelList.DataSource = systemMenu;
            channelList.DataTextField = "ChannelName";
            channelList.DataValueField = "ID";
            channelList.DataBind();
        }
        channelList.Items.Insert(0, new ListItem("全部频道", "-1", true));
        channelList.Items.Insert(1, new ListItem("顶级频道", "0", true));
    }

    /// <summary>
    /// 清理控件状态
    /// </summary>
    private void ClearInputState()
    {
        this.editID.Value = "";            //清除编辑的ID
        this.deleteID.Value = "";          //清除删除的ID
        this.editState.Value = "false";    //取消编辑状态
        RunJavascript("AddNew();", true);  //JS清空控件值
    }
    #endregion

    #region 页面加载
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //绑定频道是否末级到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchIsEnd, typeof(ChannelIsEnd));
            //绑定频道状态到下拉列表
            EnumPlus.BindDesEnumToListControl(this.searchFlag, typeof(ChannelFlag));
            //绑定所有顶级频道到下拉列表
            BindChannelList(this.searchParent);
            BindChannelList(this.drpParent);
            this.drpParent.Items.RemoveAt(0);
            //绑定列表并转到第一页
            BindAllData(this.rptDataList, 1);
        }
        else
        {
            string controlName = Request.Params.Get("__EVENTTARGET");
            string eventArgument = Request.Params.Get("__EVENTARGUMENT");
            //请求是否来自分页
            if (controlName == "pagecut" && eventArgument != "")
            {
                int current = Convert.ToInt32(eventArgument);
                //绑定列表并转到请求页
                BindDataBySearch(this.rptDataList, current);
            }
        }
    }
    #endregion

    #region 编辑事件
    protected void lbtnEdit_Click(object sender, EventArgs e)
    {
        //设置编辑状态,选项卡跳转
        this.editState.Value = "true";
        RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);

        string editID = this.editID.Value;
        if (!string.IsNullOrEmpty(editID))
        {
            ChannelModel channel = new ChannelRule().GetChannelByID(editID);

            //绑定值到页面控件
            this.txtChannelName.Value = channel.ChannelName;
            this.txtChannelEnName.Value = channel.ChannelEnName;
            this.txtChannelDes.Value = channel.ChannelDes;
            this.txtChannelUrl.Value = channel.ChannelUrl;
            this.txtOrd.Value = channel.Ord.ToString();
            this.drpParent.ClearSelection();
            this.drpParent.Items.FindByValue(channel.ParentId.ToString()).Selected = true;
            this.chkIsEnd.Checked = channel.IsEnd == (byte)ChannelIsEnd.yes ? true : false;
            this.chkFlag.Checked = channel.Flag == (byte)ChannelFlag.normal ? true : false;
            this.logoimg.Src = channel.LogoImg;
        }
    }
    #endregion

    #region 删除事件
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        int result = 0;
        string deleteItems = this.deleteID.Value;
        if (!string.IsNullOrEmpty(deleteItems))
        {
            string[] values = deleteItems.Split(',');
            foreach (string item in values)
            {
                result += new ChannelRule().DeleteChannel(item);
            }
            if (result == values.Length)
                RunJavascript("PopupMsg('success','恭喜您,删除成功！');", true);
            else
                RunJavascript("PopupMsg('error','错误,删除失败！');", true);
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 保存事件
    protected void btnSave_Click(object sender, EventArgs e)
    {
        string channelName = this.txtChannelName.Value.Trim();
        string channelEnName = this.txtChannelEnName.Value.Trim();
        string channelDes = this.txtChannelDes.Value.Trim();
        string channelUrl = this.txtChannelUrl.Value.Trim();
        int ord = int.Parse(this.txtOrd.Value);
        int parentId = int.Parse(this.drpParent.SelectedItem.Value);
        string parentName = this.drpParent.SelectedItem.Text;
        byte isEnd = this.chkIsEnd.Checked == true ? (byte)ChannelIsEnd.yes : (byte)ChannelIsEnd.no;
        byte flag = this.chkFlag.Checked == true ? (byte)ChannelFlag.normal : (byte)ChannelFlag.delete;
        string logoImg = string.Empty;
        //获取当前的logo图片地址
        string oldLogoImg = logoImg = this.logoimg.Src;

        #region 上传频道Logo图片
        string fileUpName = this.fupLogoImg.FileName;
        try
        {
            if (fileUpName != "")
            {
                //配置文件没有设置时则设置默认路径
                string configPath = ConfigurationManager.AppSettings["ChannelLogoPath"];
                if (string.IsNullOrEmpty(configPath))
                    configPath = "~/Upload/ChannelLogo/";

                //物理路径不存在则创建物理路径
                string realityPath = Server.MapPath(configPath);
                if (!Directory.Exists(realityPath))
                    Directory.CreateDirectory(realityPath);

                FileInfo fileInfo = new FileInfo(fileUpName);
                string fileType = fileInfo.Extension.ToLower();
                bool isImageFile = ".gif".Equals(fileType) || ".jpg".Equals(fileType) || ".bmp".Equals(fileType) || ".png".Equals(fileType);
                if (isImageFile)
                {
                    fileUpName = channelName + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + "-" + fileUpName;
                    logoImg = configPath + fileUpName;
                    this.fupLogoImg.SaveAs(realityPath + fileUpName);
                    
                    //上传新Logo成功后删除原Logo
                    if (oldLogoImg != "")
                    {
                        //解除缓存或目录被删除导致的错误
                        try { File.Delete(Server.MapPath(oldLogoImg)); }
                        catch (Exception ex) { }
                    }
                }
                else
                {
                    RunJavascript("PopupMsg('error','上传文件类型错误,请选择.gif、.jpg、.bmp、.png格式的图片文件！');", true);
                    RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
                    return;
                }
            }
        }
        catch (Exception ex)
        {
            RunJavascript("PopupMsg('error','错误,文件上传失败！');", true);
            return;
        }
        #endregion

        string editID = this.editID.Value;

        //父级菜单不能是自己
        if (editID == parentId.ToString())
        {
            RunJavascript("PopupMsg('error','错误,父级菜单不能是自己！');", true);
            RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            return;
        }

        //是否是修改状态
        if (this.editState.Value == "true")
        {
            //更新频道
            string sqlString = "UPDATE Channel SET ChannelName=@ChannelName, ChannelEnName=@ChannelEnName, ChannelDes=@ChannelDes,"
                +" ChannelUrl=@ChannelUrl, Ord=@Ord, ParentId=@ParentId, ParentName=@ParentName, IsEnd=@IsEnd, Flag=@Flag, LogoImg=@LogoImg WHERE ID=@ID";
            List<SqlParameter> paraList = new List<SqlParameter>();
            paraList.Add(new SqlParameter("@ChannelName", channelName));
            paraList.Add(new SqlParameter("@ChannelEnName", channelEnName));
            paraList.Add(new SqlParameter("@ChannelDes", channelDes));
            paraList.Add(new SqlParameter("@ChannelUrl", channelUrl));
            paraList.Add(new SqlParameter("@Ord", ord));
            paraList.Add(new SqlParameter("@ParentId", parentId));
            paraList.Add(new SqlParameter("@ParentName", parentName));
            paraList.Add(new SqlParameter("@IsEnd", isEnd));
            paraList.Add(new SqlParameter("@Flag", flag));
            paraList.Add(new SqlParameter("@LogoImg", logoImg));
            paraList.Add(new SqlParameter("@ID", editID));
            int result = SqlHelper.ExecuteCommand(sqlString, paraList.ToArray());
            if (result == 1)
            {
                #region 手动级联更新
                //更新子类频道
                string sqlUpdateChannel = "UPDATE Channel SET ParentName='" + channelName + "' WHERE ParentId=" + editID;
                SqlHelper.ExecuteCommand(sqlUpdateChannel);
                //更新文章
                string sqlUpdateArticle = "UPDATE Article SET ChannelName='" + channelName + "' WHERE ChannelId=" + editID;
                SqlHelper.ExecuteCommand(sqlUpdateArticle);
                //更新属于频道的上传文件
                string sqlUpdateUploadFile = "UPDATE UploadFile SET ParentName='" + channelName + "' WHERE ParentId=" + editID;
                SqlHelper.ExecuteCommand(sqlUpdateUploadFile);
                #endregion
                RunJavascript("PopupMsg('success','恭喜您,更新成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,更新失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
        }
        else
        {
            //新增频道
            ChannelModel channel = new ChannelModel();
            channel.ChannelName = channelName;
            channel.ChannelEnName = channelEnName;
            channel.ChannelDes = channelDes;
            channel.ChannelUrl = channelUrl;
            channel.Ord = ord;
            channel.ParentId = parentId;
            channel.ParentName = parentName;
            channel.IsEnd = isEnd;
            channel.Flag = flag;
            channel.LogoImg = logoImg;
            channel.CreateTime = DateTime.Now;
            int result = SqlHelper.ExecuteCommand(ChannelModel.GetInsertSQL(), channel.ToSqlParameters());
            if (result == 1)
            {
                RunJavascript("PopupMsg('success','恭喜您,新建成功！');", true);
            }
            else
            {
                RunJavascript("PopupMsg('error','错误,新建失败！');", true);
                RunJavascript("window.onload=function(){$('.box_title_tabs li').eq(1).click();};", true);
            }
        }

        //绑定列表并转到第一页
        BindAllData(this.rptDataList, 1);
    }
    #endregion

    #region 查询事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        //绑定列表并转到第一页
        BindDataBySearch(this.rptDataList, 1);
    }
    #endregion
}